package com.viethp.mt.activities;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import com.google.android.c2dm.C2DMessaging;
import com.viethp.mt.activities.R;
import com.viethp.mt.common.CommonHelper;
import com.viethp.mt.common.GlobalVariables;
import com.viethp.mt.common.MyLocationListener;
import com.viethp.mt.objects.LoginResponse;
import com.viethp.mt.objects.Position;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class ALoginScreen extends Activity implements OnClickListener {

	private static final int REQUEST_REG = 100;
	private TextView tv_signup, tv_forgot;
	private Button btn_login;
	private EditText edt_username, edt_password;
	private String username, password;

	private ProgressDialog progressDialog;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.a_login_screen);
		C2DMessaging.register(this, "aki@hirevietnamese.com");
		initComponents();
		setOnclickListener();
		setPosition();
		if (CommonHelper.getLoginMethod(getApplicationContext()) != 0) {
			Intent amain = new Intent(getApplicationContext(), AMain.class);
			amain.putExtra(
					"user_id",
					String.valueOf(CommonHelper.getUserLogin(
							getApplicationContext()).getId()));
			startActivity(amain);
			finish();
		}
		// checkLogin();
	}

	public void initComponents() {
		tv_signup = (TextView) findViewById(R.id.tv_signup);
		tv_forgot = (TextView) findViewById(R.id.tv_forgot);

		edt_username = (EditText) findViewById(R.id.edt_username);
		edt_password = (EditText) findViewById(R.id.edt_password);

		btn_login = (Button) findViewById(R.id.btn_login);

		progressDialog = new ProgressDialog(ALoginScreen.this);
		progressDialog.setCancelable(false);
	}

	public void setOnclickListener() {
		tv_signup.setOnClickListener(this);
		tv_forgot.setOnClickListener(this);

		btn_login.setOnClickListener(this);
	}

	public boolean validInput() {
		this.username = edt_username.getText().toString().trim();
		this.password = edt_password.getText().toString().trim();
		if (this.username.equals("")) {
			CommonHelper.showToast(getApplicationContext(),
					"Username is required");
			edt_username.requestFocus();
			return false;
		} else if (this.password.equals("")) {
			CommonHelper.showToast(getApplicationContext(),
					"Password is required");
			edt_password.requestFocus();
			return false;
		}
		return true;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_signup:
			Intent asignup = new Intent(getApplicationContext(),
					ASignupScreen.class);
			startActivityForResult(asignup, REQUEST_REG);
			ALoginScreen.this.overridePendingTransition(R.anim.appear,
					R.anim.disappear);
			break;
		case R.id.btn_login:
			doLogin();
			break;
		case R.id.tv_forgot:
			Intent aforgot = new Intent(getApplicationContext(),
					AForgotPWD.class);
			startActivity(aforgot);
		default:
			break;
		}

	}

	private void doLogin() {
		if (validInput()) {
			if (CommonHelper.isNetworkAvailable(ALoginScreen.this)) {
				startCallService();
			} else {
				CommonHelper.showWarning(ALoginScreen.this,
						getString(R.string.netstate));
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == REQUEST_REG) {
				CommonHelper.showToast7s(ALoginScreen.this,
						getString(R.string.regisok));
				Intent amain = new Intent(getApplicationContext(), AMain.class);
				startActivity(amain);
				finish();
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private void startCallService() {
		progressDialog.setMessage(getString(R.string.pleasewait));
		progressDialog.show();

		new Thread(new Runnable() {

			@Override
			public void run() {
				Message message = new Message();
				message.obj = callService();
				handler.sendMessage(message);

			}
		}).start();
	}

	private LoginResponse callService() {

		SoapObject userRequest = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_LOGIN);
		userRequest.addProperty("username", this.username);
		String md5Pass = CommonHelper.toMD5(this.password);
		userRequest.addProperty("password", md5Pass);
		String device_token = C2DMessaging.getRegistrationId(ALoginScreen.this);
		if (device_token.equals("")) {
			C2DMessaging.register(this, "aki@hirevietnamese.com");
			device_token = C2DMessaging.getRegistrationId(ALoginScreen.this);
			if (device_token.equals(""))
				device_token = "cantgetdevicetoken";
			else
				userRequest.addProperty("device_token", device_token);
		} else
			userRequest.addProperty("device_token", device_token);

		SoapObject request = new SoapObject(GlobalVariables.WS_NAMESPACE,
				GlobalVariables.WS_METHOD_LOGIN);
		request.addProperty(GlobalVariables.WS_METHOD_LOGIN, userRequest);
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
				SoapEnvelope.VER11);
		envelope.setOutputSoapObject(request);

		HttpTransportSE androidHttpTransport = new HttpTransportSE(
				GlobalVariables.WS_ENDPOINT,
				GlobalVariables.WS_CONNECTTION_TIME_OUT);
		SoapObject results = null;
		try {
			androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
					+ GlobalVariables.WS_METHOD_LOGIN, envelope);
		} catch (Exception e) {
			try {
				androidHttpTransport.call(GlobalVariables.WS_NAMESPACE
						+ GlobalVariables.WS_METHOD_LOGIN, envelope);
			} catch (Exception e1) {
				e1.printStackTrace();
				return null;

			}
		}
		try {
			results = (SoapObject) envelope.getResponse();
		} catch (SoapFault ex3) {
			ex3.printStackTrace();
			return null;
		}
		LoginResponse response = new LoginResponse(results);
		if (response.getUser() != null) {
			response.getUser().setPassWord(md5Pass);
		}
		return response;

	}

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			progressDialog.dismiss();

			if (msg.obj != null) {
				LoginResponse response = (LoginResponse) msg.obj;
				if (response.getErrorCode() != null) {
					CommonHelper.showWarning(ALoginScreen.this, response
							.getErrorCode().getErrMsg());
				} else {
					CommonHelper.setLoginMethod(GlobalVariables.LOGIN_BY_AA,
							ALoginScreen.this);
					CommonHelper.setUserLogin(response.getUser(),
							ALoginScreen.this);
					Intent amain = new Intent(getApplicationContext(),
							AMain.class);
					startActivity(amain);
					finish();
				}

			} else {
				CommonHelper.showWarning(ALoginScreen.this,
						getString(R.string.disconnect));
			}

		};
	};

	// position
	public void setPosition() {
		LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Location loc = mlocManager
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		LocationListener mlocListener = new MyLocationListener(
				ALoginScreen.this);

		mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
				mlocListener);
		if (loc != null) {
			Position pos = new Position();
			pos.setLon(String.valueOf(loc.getLongitude()));
			pos.setLat(String.valueOf(loc.getLatitude()));
			CommonHelper.setPosition(pos, this);
			// CommonHelper.showToast(this, ""
			// + CommonHelper.getPosition(this).getLon() + " "
			// + CommonHelper.getPosition(this).getLat());
			Log.d("LastKnowLocation", ""
					+ CommonHelper.getPosition(this).getLon() + " "
					+ CommonHelper.getPosition(this).getLat());
		} 
		// else {
		// Position pos = new Position();
		// pos.setLon(String.valueOf(GlobalVariables.lon));
		// pos.setLat(String.valueOf(GlobalVariables.lat));
		// CommonHelper.setPosition(pos, this);
		// CommonHelper.showToast(this, ""
		// + CommonHelper.getPosition(this).getLon() + " "
		// + CommonHelper.getPosition(this).getLat());
		// }
	}

}
